/**
 * User: sunny
 * Date: 13-12-20
 * Time: 下午1:14
 */
var util = require('util');
var request = require('request');
var errorlogger = require('../../config').errorlogger;
var http = require('http');
var url = require('url');
function test(url, param) {
    var options = {
        form:param
    };
    request.post(url,options,function(error,response,body) {

        if (error) {
            console.error(error);
        } else if (response.statusCode == 200) {
            console.log(body);
            var result = eval('(' + body + ')');
            console.log(util.inspect(result,false,null,true));
        } else {
            console.error('code:' + response.statusCode);
            console.log(body);
        }
    });
}
exports.test = test;
function parseResponse(url,description, error,response,body,callback) {
    if (error) {
        errorlogger.error('请求'+url+'失败',error);
        callback('请求'+description+'网络错误');
        return;
    }
    if (!response) {
        callback('请求'+description+'失败，未知错误');
        return;
    }
    if (response.statusCode != 200) {
        errorlogger.error(url, response.statusCode, body);
        callback('请求'+description+'失败['+response.statusCode+']');
        return;
    }
    callback(false,body);
}
function get(url,params,callback,pool) {
    var options = {
        qs:params
    };
	if (pool) {
		options.pool = pool;
	}
    request.get(url,options,function(error,response,body) {
        parseResponse(url,'',error,response,body,callback);
    });
}
exports.get = get;

exports.getOriginal = function(argUrl,callback,agent) {
	var parsedUrl = url.parse(argUrl, true);

	var options = {host: null, port: -1, path: null, method: 'GET'};
	options.host = parsedUrl.hostname;
	options.port = parsedUrl.port;
	options.path = parsedUrl.pathname;
	if (agent) {
		options.agent = agent;
	}

	if (parsedUrl.search) options.path += "?" + parsedUrl.search;
	var content = '';
	var req = http.request(options, function(res){
		console.log('STATUS: ' + res.statusCode);
		res.setEncoding('utf8');
		res.on('data', function(chunk){
			content+= chunk;
		});
		res.on('error', function(err){
			errorlogger.error('RESPONSE ERROR: ' , err);
			callback(err);
		});
		res.on('end',function() {
			callback(false,content);
		});
	});

	req.on('error', function(err){
		errorlogger.error('REQUEST ERROR: ' , err);
		callback(err);
	});
	req.end();
}
